<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>保质期计算器</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        input, button {
            margin: 5px 0;
            padding: 10px;
            font-size: 16px;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
            width: calc(100% - 24px); /* Adjust width to account for padding */
        }
        button {
            background-color: #4CAF50;
            color: white;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #45a049;
        }
        label {
            font-weight: bold;
        }
    </style>
</head>
<body>
    <h1>保质期计算器</h1>
    <label for="startDate">开始日期 (YYYYMMDD):</label>
    <input type="text" id="startDate" placeholder="例如：20230101"><br>
    
    <label for="shelfLife">保质期 (天):</label>
    <input type="number" id="shelfLife" placeholder="例如：30"><br>
    
    <button onclick="calculateExpiry()">计算</button>
    
    <p id="result"></p>

    <script>
        function calculateExpiry() {
            const startDateInput = document.getElementById('startDate').value;
            const shelfLifeInput = parseInt(document.getElementById('shelfLife').value, 10);
            const resultElement = document.getElementById('result');

            if (!startDateInput || isNaN(shelfLifeInput)) {
                resultElement.textContent = '请输入有效的开始日期和保质期。';
                return;
            }

            const startDate = new Date(
                parseInt(startDateInput.substring(0, 4), 10),
                parseInt(startDateInput.substring(4, 6), 10) - 1,
                parseInt(startDateInput.substring(6, 8), 10)
            );

            const expiryDate = new Date(startDate);
            expiryDate.setDate(expiryDate.getDate() + shelfLifeInput);

            const today = new Date();
            const timeDiff = expiryDate - today;
            const dayDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));

            if (dayDiff < 0) {
                resultElement.textContent = `已过期 ${Math.abs(dayDiff)} 天。`;
            } else {
                resultElement.textContent = `还有 ${dayDiff} 天过期。`;
            }
        }
    </script>
</body>
</html>